//
// BinTest
//
// This program tests a random number generator by running it n times
// with m bins for sorting over the interval [0, 1].
//


#import "Random.h"
#import <math.h>
#import <stdio.h>
#import <stdlib.h>


#define FUNC		doublepeakfunc


#define DEFAULT_N	1000
#define DEFAULT_M	20


#define MAX_BAR		40


#define TAN_PI	3.14159267
#define TAN_2DIVPI	(2.0 / TAN_PI)

double tanfunc(double x)
{
//    return (tan(TAN_2DIVPI * x - 0.5) + 0.5);
    return (1 + tan((x - 0.5) / TAN_PI)) / 2.0;
}


#define SINONE		0.8414709848

double sinfunc(double x)
{
    return (sin(x) / SINONE);
}


double linefunc(double x)
{
    return (x);
}


double squarefunc(double x)
{
    return (x * x);
}


double parafunc(double x)
{
    double y = x - 1.0;
    
    return (1 - (y * y));
}


double doublepeakfunc(double x)
{
    return (1 + sin((x / TAN_PI) - 0.5)) / 2.0;
}


int main(int argc, char *argv[])
{
    id		myRand;				// Random number generator.
    int		n;				// Quantity of numbers to generate.
    int		m;				// Number of bins in which to sort them.
    int		max;				// Size of largest bin.
    int		i;				// Generic loop variable.
    int		j;				// Generic loop variable.
    double	x;				// The random number.
    int		slot;				// The sorted position of a number.
    int		barsize;			// The length of a result bar.
    int		*bin;				// The bin array (dynamically allocated).
    
    myRand = [[Random alloc] init];
    
    switch(argc) {
        case 2:
	    sscanf(argv[1], "%d", &n);;
	    m = DEFAULT_M;
	    break;
	case 3:
	    sscanf(argv[1], "%d", &n);;
	    sscanf(argv[2], "%d", &m);;
	    break;
	default:
	    n = DEFAULT_N;
	    m = DEFAULT_M;
	    break;
    }
    
    //
    // Allocate and initialize slot array:
    //
    
    bin = (int *)malloc(m * sizeof(int));
    for(i = 0; i < m; i++)
        bin[i] = 0;
    
    //
    // Make n random numbers:
    //
        
    for(i = 0; i < n; i++) {
        x = [myRand gaussian];
	
	slot = (int)floor(x * m);
	if((slot >= 0) && (slot < m)) {		// If it is in range,
	    if((++bin[slot]) > max) {		//   count it.
		max = bin[slot];
	    }
	}
    }
    
    //
    // Print the results:
    //
    
    for(i = 0; i < m; i++) {
        printf("%1.6f - %1.6f: %6d:", i * (1.0 / m), (i + 1) * (1.0 / m), bin[i]);
	
	barsize = (int)((double)bin[i] / ((double)max / (double)MAX_BAR));
	for(j = 0; j < barsize; j++)
	    printf("*");
	printf("\n");
    }
    
    printf("Max = %d\n\n", max);
    
    //
    // Clean up:
    //
    
    free(bin);
    
    //
    // Return to caller:
    //
    
    return 0;
}


//
// End of file.
//